package br3akr.DeadlyDinnerParty.Server.Engine;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;

import br3akr.DeadlyDinnerParty.Server.World.World;

public class ServerThread extends Thread {
    private Socket socket = null;
	boolean connected = true;
	ObjectOutputStream out;
	BufferedReader in;
	Session session;
    
    public ServerThread(Socket socket, World world) {
    	super("ServerThread");
    	this.socket = socket;
    }
    
    public void run() {
		try {
		    out = new ObjectOutputStream(socket.getOutputStream());
		    in = new BufferedReader(
					    new InputStreamReader(
					    socket.getInputStream()));
                        
            session = new Session(out);
            session.login();
            String inputLine = null;

	    	while ((inputLine = in.readLine()) != null) {
	    		session.handleInput(inputLine);
	    		
	    		if (!session.isRunning()) {
	    			break;
	    		}
	    	}
		} catch (SocketException e) {
			System.out.println("Lost connection to: " + session.getPlayerName());
		} catch (Exception e) {
		    e.printStackTrace();
		} finally {
		    Server.world.removeOnlinePlayer(session);
		    
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					// ignore
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (Exception e) {
					// ignore
				}
			}
		}
    }
}